#-*-encoding:utf-8-*-

import csv

def parse_feature(line):
    return map(float, line)

def read_csv(fname, parse, delimiter=',', header=True):
    ret = []

    with open(fname, "rb") as f:
        _f = csv.reader(f, delimiter=delimiter)
        for line in _f:
            if header:
                header = False
                continue
            ret.append(parse(line))
    return ret

def load_csv(fname, parse, delimiter=",", header=True):
    ret = []
    with open(fname, "rb") as f:
        _f = csv.reader(f, delimiter=delimiter)
        for line in _f:
            if header:
                ret.append(line)
                header=False
                continue
            ret.append(parse(line))
    return ret

def read_log(fname, parse_):
    ret = []

    with open(fname, "rb") as f:
        for line in f:
            ret.append(parse_(line))
    return ret


def format_string(entry):
    return ','.join(map(str, entry))

def write_csv(fname, dataset, format_func=format_string, header=None):
    with open(fname, "wb") as f:
        if header:
            f.write("{0}\n".format(header))
        for item in dataset:
            f.write("{0}\n".format(format_func(item)))


def write_roc_(roc_file, results, key, headers):
    with open(roc_file, "wb") as f:
        f.write("times,{0}\n".format(",".join(map(str, headers))))
        for i, entryset in enumerate(results):
            line = [i]
            for name in headers:
                line.append(entryset[name][key])
            f.write("{0}\n".format(",".join(map(str, line))))